<template>
	<view class="matchmain animated fadeIn faster">
		<view class="position-fixed w-100 z-index-100 pb-1" :style="{'paddingTop':$store.state.statusBarHeight+'px','backgroundColor':bgcolor}">
			<view class="d-flex d-flex-middle d-flex-between" :style="{'height': $store.state.titleBarHeight + 'px'}">
				<view class="pl-2" @click="goBack"><text class="iconfont icon-31fanhui1 font30 colorfff"></text></view>
				<view class="colorfff">选择搭子</view>
				<text class="iconfont icon-31fanhui1 font30 colorfff vhiden"></text>
			</view>
		</view>
		<view :style="{paddingTop:$store.state.statusBarHeight+'px',height: $store.state.titleBarHeight + 'px'}"></view>
		<view class="card" style="width: 90%; margin: 140rpx auto 0;">
			<view class="card_item mb-5 d-flex d-flex-middle d-flex-between" :style="{backgroundImage: `url(${i.background})`}" v-for="i in DaziCardList" :key="i.id">
				<view class="d-flex">
					<view class="mr-2 mb-2" style="margin-left: 60rpx;">
						<image :src="i.icon" style="width: 70rpx; height: 70rpx;"></image>
					</view>
					<view class="colorfff mb-2">
						<text class="font28 font-bold">{{i.name}}</text>
						<view class="d-flex">
							<text class="font24">{{i.description}}</text>
							<view class="ml-1 d-flex-btn">
								<image src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/%E7%BB%84%202585.png" style="width: 30rpx; height: 25rpx;"></image>
							</view>
						</view>
					</view>
				</view>
				<view v-if="!i.hasBalanceFlag" class="colorfff py-1 px-2 rounded40 linerbg mr-5 mt-3 font24" @click="OpenpurchasePopup(i)">购买并使用</view>
				<view v-else class="colorfff py-1 px-2 rounded40 linerbg mr-5 mt-3 font24">使用中</view>
			</view>
		</view>
		<view class="card" style="width: 90%; margin: 0 auto;">
			<view class="card_item mb-5 d-flex d-flex-middle d-flex-between" :style="{backgroundImage: `url(${i.bg})`}" v-for="i in DaziCardData" :key="i.id">
				<view class="d-flex">
					<view class="mr-2 mb-2" style="margin-left: 60rpx;">
						<image :src="i.image" style="width: 70rpx; height: 70rpx;"></image>
					</view>
					<view class="colorfff mb-2">
						<text class="font28 font-bold">{{i.title}}</text>
						<view class="d-flex">
							<text class="font24">{{i.desc}}</text>
							<view class="ml-1 d-flex-btn">
								<image src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/%E7%BB%84%202585.png" style="width: 30rpx; height: 25rpx;"></image>
							</view>
						</view>
					</view>
				</view>
				<view v-if="!i.hasBalanceFlag" class="colorfff py-1 px-2 rounded40 linerbg mr-5 mt-3 font24" @click="gotoMemberPage">购买并使用</view>
				<view v-else class="colorfff py-1 px-2 rounded40 linerbg mr-5 mt-3 font24">使用中</view>
			</view>
		</view>
		<uni-popup ref="purchasePopup" @change="PopupStatusChange"  type="bottom" background-color="#fff" border-radius="10px 10px 0 0">
			<radio-group class="PayOptions d-flex-between pt-2" v-for="(item, index) in PayList" :key="item.id" @change="ChangePayOpt(index)">
			  <label class="d-flex d-flex-middle d-flex-between">
			    <view class="icon">
			      <image :src="item.icon"></image>
			    </view>
			    <view class="option mr-1" style="margin-bottom: 4rpx;">{{item.name}}</view>
			    <view v-if="item.desc" class="font22 px-3 rounded10" style="color: #FF9645; background: #f9e7c9;">{{item.desc}}</view>
			  </label>
			  <radio :value="index" :checked="item.checked" style="transform:scale(0.6);"></radio>
			</radio-group>
			<view  class="btn ml-2 colorfff linerbg" style="width: 75%;" @click="confirm">立即以{{PayMount}}开通</view>
			<view class="d-flex d-flex-center d-flex-middle">
				<label class="d-flex d-flex-middle" @click="changeAgree()">
					<!-- <checkbox :checked="isChecked" style="transform:scale(0.6)" @click="isChecked = !isChecked"></checkbox> -->
					<checkbox :checked="isagree" style="transform:scale(0.6);margin-top: 3px;" @click="changeAgree()" ></checkbox>
					<view class="font22" style="color: #717071;">我已阅读并同意</view>
				</label>
				<view class="font22" style="color: #2CA6E0;">《超级尊贵玩家服务协议》</view>
				<view class="font22" style="color: #717071;">和</view>
				<view class="font22" style="color: #2CA6E0;">《连续订阅服务协议》</view>
			</view>
		</uni-popup>
		<view v-if="IsShowCoupon" class="position-fixed top-0 left-0 right-0 bottom-0" style="background: rgba(0, 0, 0, .4); z-index: 1001;">
						<view class="position-relative bg-fff" style="top: 50%; left: 50%; transform: translate(-50%,-50%); border-radius:10px 10px 10px 10px">
							<view class="coupon-list">
													  <view class="font32 text-center mt-1 mb-3">您有以下的优惠券可以使用</view>
							  <view v-for="(i, index) in couponList" :key="index" class="d-flex" style="height: 120rpx; width: 90%; margin: 0 auto 20rpx;">
							    <view class="Cover rounded10" style="width: 90rpx; height: 100%;">
							      <view class="d-flex d-flex-bottom d-flex-center colorfff" style="margin-top: 15rpx;">
							        <view style="margin-bottom: 5rpx;">￥</view>
							        <view class="font-bold" style="font-size: 40rpx;">{{ i.amount }}</view>
							      </view>
							      <view class="font16 mt-1 colorfff text-center">满{{ i.limitUseAmount == 0 ? i.amount : i.limitUseAmount }}元可用</view>
							    </view>
							    <view class="Coupon_item d-flex-middle d-flex bg-fff rounded10" style="flex: 1; padding: 10rpx;">
							      <view class="d-flex d-flex-column ml-3" style="flex: 1;">
							        <view class="font24 mt-1">{{ i.name }} </view>
							        <view class="font24" style=" flex: 1;color: #b5b5b5;">有效期:{{ i.assetsExpireTime }}到期</view>
							      </view>
							      <view class="btn1 colorfff mr-3 px-2 rounded10 font20" @click="touse(i.assetsId)">选择</view>
							    </view>
							  </view>
													
													
													<view class="btn ml-2  colorfff" style="width: 75%; background-image: linear-gradient(-90deg, #f7880c 0%, #fe7039 40%, #fe536f 60%, #fe4594 90%, #f73ea0 100%);" @click="unuse">不使用优惠券</view>
													
							</view>
						</view>
		 </view>
	</view>
</template>

<script>
	import { manner } from "@/util/manner.js";
	import { DaziApi } from "../../http/Dazi";
	import { PayApi } from '../../http/PayApi';
	
	export default {
		data() {
			return {
				bgcolor:'transparent',
				DaziCardList: [],
				PayMount: 0,
				isagree: false,
				orderStr:null,
				PayRecipient: null,
				param:{},
				payMethod:0,
				IsShowCoupon:false,
				DaziCardData: [{
					id: 4,
					title: '开通会员享全部服务',
					desc: '奖励',
					image: 'https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/%E7%BB%84%202024.png',
					icon: 'https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/%E7%BB%84%202585.png',
					bg: 'https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/%E7%BB%84%203415%402x.png',
					hasBalanceFlag: false
				}],
				PayList: [
					{
						id: 3,
						icon: 'https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20241115141319.png',
						name: '支付宝',
						desc: '推荐',
						value: 'Alipay',
						checked: true
					},
					{
						id: 2,
						icon: 'https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/Pay-Wechat.png',
						name: '微信',
						desc: '',
						value: 'Wechat',
						checked: false
					},
					{
						id: 1,
						icon: 'https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/%E7%BB%84%20554.png',
						name: '嗒币',
						desc: '',
						value: 'DaBi',
						checked: false
					}
				],
				payType: null,
				PackageId: null,
				couponList:[],
				price:0,
				orderNo: null,
				device:true,//设备
				 WxpayParams:{},//微信支付参数
			}
		},
		onPageScroll(e) {
			let scrollTop = e.scrollTop
			if (scrollTop > 10) {
				this.bgcolor = '#191635'
			}else{
				this.bgcolor = 'transparent'
			}
		},
		methods: {
			
			
			goBack(){
				manner.goBack()
			},
			gotoMemberPage() {
				uni.navigateTo({
					url: '/pagesMain/member/member'
				})
			},
			
			changeAgree() {
				this.isagree = !this.isagree
				console.log(this.isagree );
			},
			PopupStatusChange(e) {
				// 关闭弹窗将支付选项恢复默认
				if(!e.show) {
					setTimeout(() => {
						this.PayList.forEach((i, index) => {
							if(index === 0) {
								this.PayList[index].checked = true
							} else {
								this.PayList[index].checked = false
							}
						})
					},500)
				}
			},
			ChangePayOpt(dex) {
				this.PayList[dex].checked = true;
				// 将其他选项设置为未选中
				this.PayList.forEach((i, index) => {
					if (dex !== index) {
					this.PayList[index].checked = false;
					}
				});
				if((dex==0 && this.device) || dex==1 && this.device) { // 安卓价格
					this.PayMount = '￥' + this.PayRecipient.androidPrice
				} else if(dex==0 && !this.device) { // 苹果价格
					this.PayMount = '￥' + this.PayRecipient.iosPrice
				}
				if(dex==2 && this.device) { // 安卓嗒币价格
					this.PayMount = this.PayRecipient.androidCoinPrice + '搭币'
				} else if(dex==2 && !this.device) { // 苹果嗒币价格
					this.PayMount = this.PayRecipient.iosCoinPrice + '搭币'
				}
			}, 
			async queryDaziCard() {
				let params = {
					pageIndex: 1,
					pageSize: 30
				}
				const res = await DaziApi.DaziCard(params)
				this.DaziCardList = res.records
			},
			OpenpurchasePopup(item) {
				this.$refs.purchasePopup.open('bottom')
				if(this.device){
					 this.PayMount ='￥'+item.androidPrice
				}else{
					this.PayMount='￥'+item.iosPrice
				}
				this.price=this.device?item.androidPrice:item.iosPrice
				this.PayRecipient = item
				console.log(this.PayRecipient.id,111111111111);
			},
			async getCoupon(){//查询可用优惠券
			 const param = {
			        resourceType: 5,
			        amount: this.price
			      };
				  this.couponList=[];
			      const res = await PayApi.getCoupon(param);
			      this.couponList = res;
				console.log(this.couponList);
				
				
				
				
			},
			unuse(){
				this.IsShowCoupon=false;
				this.param.sourceType=this.device? 1 : 2;
				this.param.id=this.PayRecipient.id;
				this.param.type=this.PayRecipient.type
				 
				 
				 that.CreateOrder(that.payMethod);
			},
			touse(id){//使用优惠券
			  console.log(id);
				      // 选择优惠券后继续支付流程
					
					  this.param.couponAssetsId=id;
					  this.param.sourceType=this.device? 1 : 2;
					  this.param.id=this.PayRecipient.id;
					  this.param.type=this.PayRecipient.type
					  console.log(this.param);
					  
					  this.CreateOrder(this.payMethod);
					  
				      this.IsShowCoupon=false;
				    
				
			},
			OpencouponPopup(){
				this.IsShowCoupon = true
			},
			async confirm() {
				let that = this
				console.log(that.isagree);
				if(!that.isagree) {
					uni.showToast({
						icon: "none",
						title:'请勾选服务协议',
						duration:1500
					});
					
					return
				}
				
				
				that.PayList.forEach(i => {
					if(i.checked) {
						
						that.payMethod = i.id,
						 that.payType=(i.id == 1)? 1 : 2
					}
				})
				
				
				await that.getCoupon();
				
				
				// 根据优惠券情况处理
				if (that.couponList.length > 0) {
				  that.OpencouponPopup();
				} else {
				 this.param.sourceType=this.device? 1 : 2;
				 this.param.id=this.PayRecipient.id;
				 this.param.type=this.PayRecipient.type
				  
				  
				  that.CreateOrder(that.payMethod);
				}
			},
			payByWxpay() {
						    uni.requestPayment({
						        "provider": "wxpay", // 微信支付
								"orderInfo": {
						        "appid": this.WxpayParams.appid,
						        "timestamp":this.WxpayParams.timestamp,
						        "noncestr": this.WxpayParams.noncestr,
								"package": "Sign=WXPay", 
								"partnerid": this.WxpayParams.partnerId,
						        "prepayid": this.WxpayParams.prepayId, 
						        "sign": this.WxpayParams.sign
								},
								
						        success: (res) => {
						            console.log('支付成功', res);
									 uni.hideLoading();
									 this.queryDaziCard()
						            // 支付成功的处理逻辑
						            uni.showToast({
						                title: '支付成功',
						                icon: 'success',
						                duration: 2000
						            });
						        },
			       fail: (err) => {
			                   console.log('支付失败，错误信息：', err);
			                   if (err.errCode === 'xxx') { 
			                       // 可以根据不同的 errCode 进行不同的处理，这里的 xxx 是具体的错误码，例如用户取消支付的错误码
			                       console.log('用户取消支付');
			                   } else if (err.errCode === 'yyy') { 
			                       // 另一种错误码 yyy 的处理
			                       console.log('签名错误，请联系客服');
			                   } else {
			                       console.log('其他支付错误，请重试或联系客服');
			                   }
			                   uni.showToast({
			                       title: '支付失败',
			                       icon: 'none',
			                       duration: 2000
			                   });
			               }
			    });
			},
			payByAlipay() {//支付宝的支付
					   
			const orderStr = this.orderStr;
			if (!orderStr) {
			    console.error('订单字符串为空，无法进行支付');
			    return;
			}
			
			// 调用 uni.requestPayment 方法
			uni.requestPayment({
			    provider: 'alipay', // 指定支付提供商为支付宝
			    orderInfo: orderStr, // 订单信息
			    success: (res) => {
			        console.log('支付成功:', res);
			        uni.hideLoading();
			        this.queryDaziCard()
					uni.showToast({
					    title: '支付成功',
					    icon: 'none', // 使用'none'图标，只显示文字
					    duration: 1000 // 显示持续时间
					  });
			    },
			    fail: (err) => {
			        console.error('支付失败:', err);
			       uni.showToast({
			           title: '支付失败',
			           icon: 'none', // 使用'none'图标，只显示文字
			           duration: 1000 // 显示持续时间
			         });
			    }
			});
					},
			// 创建订单
			async CreateOrder(payMethod) {
				
				// let params = {
				// 	sourceType: this.device?'1':'2',
				// 	id:this.PayRecipient.id,
				// 	type: this.PayRecipient.type
				// }
				
				
				let res = await PayApi.functionCard(this.param)
				this.Pay(res.orderNo,payMethod)
			},
			// 支付
			async Pay(orderNo, payMethod) {
				let params = {
					orderNo: orderNo,
					payMethod: payMethod,
					payType: this.payType
				}
				const res = await PayApi.Pay(params)
				console.log(res);
				console.log(payMethod);
				if(payMethod==3){
					this.orderStr=res.params.orderStr;
					this.payByAlipay();	
						return
				}
				if(payMethod==2){//微信支付
					this.WxpayParams={};
					this.WxpayParams=res.params;
					
					this.payByWxpay();
					return
				}
				if(params.payType==1){
					console.log(res.paySuccess);
					if(res.paySuccess){
						uni.showToast({
						    title: '购买成功',
						    icon: 'none', // 使用'none'图标，只显示文字
						    duration: 1000 // 显示持续时间
						  });
						this.$refs.purchasePopup.close();
						this.queryDaziCard();
					}
				}	
				
				
			}
		},
		onLoad() {
			this.queryDaziCard();
			let systemInfo = uni.getSystemInfoSync();
			if (systemInfo.platform === 'ios') {
				this.device=false;
			    console.log('当前设备是苹果设备');
			} else if (systemInfo.platform === 'android') {
				this.device=true;
			    console.log('当前设备是安卓设备');
			}
			
		}
	}
</script>

<style scoped lang="scss">
	.coupon-list {
	    padding: 20rpx;
	  }
	   .Cover {
	      width: 90rpx;
	      height: 100%;
	      border-right: 1px dashed #f5f5f5;
	      background-image: linear-gradient(135deg, #f7880c 0%, #fe7039 40%, #fe536f 60%, #fe4594 90%, #f73ea0 100%);
	    }
	  
	    .Coupon_item {
	      flex: 1;
	      box-shadow: 3px 3px 3px rgba(0, 0, 0, .1);
	    }
	  
	    .btn1 {
	      height: 40rpx !important;
	      line-height: 40rpx !important;
	      background-image: linear-gradient(-90deg, #f7880c 0%, #fe7039 40%, #fe536f 60%, #fe4594 90%, #f73ea0 100%);
	    }
.matchmain{
	background-image: url('https://168809.oss-cn-hangzhou.aliyuncs.com/community/temp/machbg.png');
	background-repeat: no-repeat;
	background-size: cover;
	background-position: 0 100%;
	min-height: 100vh;
}
.metting-box {
	width: 98%;
	height: 940rpx;
	left: 50%;
	transform: translateX(-50%);
	border-radius: 50rpx 50rpx 0 0;
	background-color: #fff;
	overflow: hidden;
}
.linerbg-b {
	background: linear-gradient( 180deg, #61D1E5 0%, rgba(106,211,230,0.94) 10%, rgba(131,219,234,0.78) 29%, rgba(172,230,241,0.52) 54%, rgba(227,247,250,0.17) 86%, rgba(255,255,255,0) 100%);
}
.colorman{
	color:#5db0fe
}
.card_item {
	width: 100%;
	height: 180rpx;
	background-size: contain;
	background-repeat: no-repeat;
}
.PayOptions {
		width: 680rpx;
		margin: 0 auto;
		display: flex;
		align-items: center;
		margin-top: 30rpx;
		.icon {
			margin-right: 26rpx;
			image {
				width: 64rpx;
				height: 64rpx;
			}
		}
		.option {
			color: #231815;
			font-size: 28rpx;
		}
	}
.btn {
	margin: 40rpx auto 20rpx;
	text-align: center;
	font-size: 30rpx;
	height: 87rpx;
	line-height: 87rpx;
	border-radius: 50rpx;
}
</style>
